package com.sqn.controller;

import com.sqn.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {

    @RequestMapping({"/", "/index"})
    public String toIndex(Model model) {
        model.addAttribute("msg", "hello,Shiro");
        return "index";
    }

    @RequestMapping("/user/add")
    public String add() {
        return "user/add";
    }

    @RequestMapping("/user/update")
    public String update() {
        return "user/update";
    }

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/login")
    public String login(@RequestParam("rememberMe") boolean rememberMe, @RequestParam("username") String name, @RequestParam("password") String password, Model model) {
        try {
            //获取当前的用户
            Subject subject = SecurityUtils.getSubject();
            //封装用户的登录数据
            UsernamePasswordToken token = new UsernamePasswordToken(name, password);
            //设置记住我
            ((UsernamePasswordToken) token).setRememberMe(rememberMe);
            //执行登录方法，如果没有异常就说明OK了
            subject.login(token);
            //从Shiro中拿出User对象
            User user = (User) SecurityUtils.getSubject().getPrincipal();
            System.out.println("----------" + ((UsernamePasswordToken) token).isRememberMe());
            System.out.println("登录成功！");
        } catch (UnknownAccountException accountException) {
            // 用户名不存在
            model.addAttribute("msg", "用户名错误");
            return "login";
        } catch (IncorrectCredentialsException e) {
            // 密码错误
            model.addAttribute("msg", "密码错误");
            return "login";
        }
        //重定向到另一个控制器请求返回主页面
        return "redirect:/index";
    }

    @RequestMapping("/noAuth")
    @ResponseBody
    public String unAuthorized() {
        return "未经授权无法访问此页面！";
    }

}
